﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interactivity;
using Fluffy.Library.Comparers;

namespace Fluffy.Library.Behaviors
{
	public class ColumnWithCustomSortingBehavior : Behavior<DataGrid>
	{
		public object Column { get; set; }
		public IComparerWithDirection Comparer { get; set; }

		protected override void OnAttached()
		{
			base.OnAttached();

			AssociatedObject.Sorting += OnSorting;
		}

		protected override void OnDetaching()
		{
			base.OnDetaching();

			AssociatedObject.Sorting -= OnSorting;
		}

		private void OnSorting(object sender, DataGridSortingEventArgs e)
		{
			DataGridColumn column = e.Column;

			if (Comparer == null)
				return;

			if (!Equals(column.Header, Column))
				return;

			ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
			column.SortDirection = direction;

			ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(AssociatedObject.ItemsSource);

			Comparer.Direction = direction;
			lcv.CustomSort = Comparer;

			e.Handled = true;
		}
	}
}
